package com.lingxiaoti.hmbratelimiter.core.aop;

import com.lingxiaoti.hmbratelimiter.core.enums.LimitType;
import com.lingxiaoti.hmbratelimiter.core.annotation.RateLimit;
import com.lingxiaoti.hmbratelimiter.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 限流切面处理
 */
//@Component
@Aspect
@Slf4j
public class RateLimiterAspect {

    private static final String UNKNOWN = "unknown";

    @Autowired
    private RedissonClient redissonClient;

    // 指定切入点
    @Pointcut("execution(public * *(..)) && @annotation(com.lingxiaoti.hmbratelimiter.core.annotation.RateLimit)")
    public void pointcut() {
    }

    /**
     * 切面处理, 环绕通知
     *
     * @param joinPoint 切面对象
     * @throws NoSuchMethodException 【】
     * @throws InterruptedException  【】
     */
    @Around("pointcut()")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName(); // 方法名
        Class<?> classTarget = joinPoint.getTarget().getClass(); // 切入点的目标类
        Class<?>[] par = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        Method objMethod = classTarget.getMethod(methodName, par);
        RateLimit rateLimit = objMethod.getAnnotation(RateLimit.class);
        if (rateLimit == null) {
            return joinPoint.proceed();
        }
        String name = rateLimit.name();
        //
        int duration = rateLimit.duration(); // 限流时间
        int limit = rateLimit.limit(); // 限流次数
        LimitType limitType = rateLimit.limitType();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 根据限流类型获取不同的key ,如果不传我们会以方法名作为key
        String key;
        switch (limitType) {
            case IP:
                key = getIpAddress();
                break;
            case DEFAULT:
                key = name;
                if (StringUtils.isBlank(key)) {
                    key = signature.getDeclaringTypeName() + "." + signature.getName();
                }
                break;
            default:
                key = signature.getDeclaringTypeName() + "." + signature.getName();
        }
        log.info("限流锁key={}", key);
        // 获取限流器
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        // 设置限流策略(例如每秒钟不超过10个请求)
        // RateType.OVERALL 全局，RateType.PER_CLIENT每个客户端, trySetRate初始化限流策略到redis, 再次执行不会进行修改
        rateLimiter.trySetRate(RateType.OVERALL, limit, duration, RateIntervalUnit.SECONDS);
        // 超时时间5秒
        boolean acquire = rateLimiter.tryAcquire(1, 500, TimeUnit.MILLISECONDS);
//        boolean acquire = rateLimiter.tryAcquire(1);
        if (!acquire) {
//            throw new BizException("Too Many Requests");
            throw new BizException("访问过于频繁，请稍后重试！");
        }
        return joinPoint.proceed();
    }

    public String getIpAddress() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}